package com.hooper.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hooper.hosp.model.hosp.BookingRule;
import com.hooper.hosp.model.hosp.Department;
import com.hooper.hosp.model.hosp.Hospital;
import com.hooper.hosp.model.hosp.Schedule;
import com.hooper.hosp.repository.ScheduleRepository;
import com.hooper.hosp.service.DepartmentService;
import com.hooper.hosp.service.HospService;
import com.hooper.hosp.service.ScheduleService;
import com.hooper.hosp.utils.MongoPageUtils;
import com.hooper.hosp.vo.hosp.BookingScheduleRuleVo;
import com.hooper.hosp.vo.hosp.ScheduleOrderVo;
import com.hooper.hosp.vo.hosp.ScheduleQueryVo;
import com.hooper.hospital.common.exception.HospitalException;
import com.hooper.hospital.common.utils.DateUtils;
import com.hooper.hospital.common.utils.ObjectUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.hooper.hospital.common.constant.HospConstant.NOT_DELETED;
import static com.hooper.hospital.common.constant.HospConstant.TIME_NOW;
import static com.hooper.hospital.common.result.ResultCodeEnum.NO_SUCH_DATA;
import static com.hooper.hospital.common.result.ResultCodeEnum.PARAM_EMPTY;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/09/28/18:32
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ScheduleServiceImpl implements ScheduleService {

    private final ScheduleRepository scheduleRepository;
    private final MongoTemplate mongoTemplate;
    private final HospService hospService;
    private final DepartmentService departmentService;

    @Override
    public void saveOrUpdate(Map<String, Object> map) {
        //covert json to java obj
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(map), Schedule.class);

        String hosScheduleId = schedule.getHosScheduleId();

        Schedule dbSchedule = scheduleRepository.findScheduleByHosScheduleId(hosScheduleId);

        if (dbSchedule == null) {
            //if the data is new
            schedule.setIsDeleted(NOT_DELETED);
            schedule.setCreateTime(TIME_NOW);
        } else {
            schedule.setId(dbSchedule.getId());
        }
        scheduleRepository.save(schedule);
    }

    @Override
    public Page<Schedule> pageSchedule(int page, int limit, ScheduleQueryVo queryVo) {
        Pageable pageAble = MongoPageUtils.getPageable(page, limit);

        //the Example obj need Department obj, use BeanUtils to copy
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(queryVo, schedule);
        //config fuzzy query
        Example<Schedule> example = MongoPageUtils.getExample(schedule);
        //query
        return scheduleRepository.findAll(example, pageAble);
    }


    @Override
    public void removeByHoscodeAndScheduleId(String hoscode, String scheduleId) {
        scheduleRepository.removeByHoscodeAndHosScheduleId(hoscode, scheduleId);
    }

    @Override
    public Map<String, Object> findAllByHoscodeAndDepcode(int currentPage, int pageSize, String hoscode, String depcode) {
        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2 根据工作日workDate期进行分组
        Aggregation agg = Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),
                //分组字段
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        //3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //4 实现分页
                Aggregation.skip((currentPage - 1) * pageSize),
                Aggregation.limit(pageSize)
        );
        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //把日期对应星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = DateUtils.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        result.put("total", total);

        //获取医院名称
        String hosName = hospService.getHospitalByHoscode(hoscode).getHosname();
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("baseMap", baseMap);

        return result;
    }

    @Override
    public List<Schedule> getDetail(String depcode, String hoscode, String workDate) {
        if (StringUtils.isAnyBlank(depcode, hoscode, workDate)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        List<Schedule> scheduleList = scheduleRepository.findAllByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        return scheduleList.stream().peek(item -> {
            Map<String, Object> param = item.getParam();
            DateTime dateTime = new DateTime(item.getWorkDate());
            param.put("datOfWeek", DateUtils.getDayOfWeek(dateTime));
            param.put("hosname", hospService.getHospitalByHoscode(hoscode).getHosname());
            param.put("depname", departmentService.getByDepcode(depcode).getDepname());
        }).collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        if (StringUtils.isAnyBlank(hoscode, depcode) || ObjectUtils.isAnyNull(page, limit)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        Map<String, Object> result = new HashMap<>();
        //获取医院信息
        Hospital hospital = hospService.getHospitalByHoscode(hoscode);
        if (hospital == null) {
            throw new HospitalException(NO_SUCH_DATA);
        }
        //获取该医院的预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        //获取分页的日期数据
        IPage<Date> datePage = getDatePage(page, limit, bookingRule);
        List<Date> dateList = datePage.getRecords();
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                //分组字段
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleRuleVoList = aggregationResults.getMappedResults();
        if (CollectionUtils.isEmpty(scheduleRuleVoList)) {
            return null;
        }
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = scheduleRuleVoList.stream().
                collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, bookingScheduleRuleVo -> bookingScheduleRuleVo));
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if (null == bookingScheduleRuleVo) {
                // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = DateUtils.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == len - 1 && page == datePage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", datePage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospService.getHospitalByHoscode(hoscode).getHosname());
        //科室
        Department department = departmentService.getByDepcode(depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;

    }

    @Override
    public Schedule getScheduleById(String scheduleId) {
        if (StringUtils.isEmpty(scheduleId)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        return packageSchedule(scheduleRepository.findScheduleById(scheduleId));
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        if (StringUtils.isEmpty(scheduleId)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //获取排班信息
        Schedule schedule = scheduleRepository.findScheduleById(scheduleId);
        if (schedule == null) {
            throw new HospitalException(NO_SUCH_DATA);
        }
        //获取医院信息
        String hoscode = schedule.getHoscode();
        Hospital hospital = hospService.getHospitalByHoscode(hoscode);
        if (hospital == null) {
            throw new HospitalException(NO_SUCH_DATA);
        }
        //将信息封装到vo中
        scheduleOrderVo.setHosname(hospital.getHosname());
        BeanUtils.copyProperties(schedule, scheduleOrderVo, "hosname");
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setDepname(departmentService.getByDepcode(schedule.getDepcode()).getDepname());
        BookingRule bookingRule = hospital.getBookingRule();
        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 根据周期获取日期分页
     *
     * @param page        当前页
     * @param limit       默认大小为 7
     * @param bookingRule 预约规则
     * @return
     */
    private IPage<Date> getDatePage(Integer page, Integer limit, BookingRule bookingRule) {
        //获取预约周期，根据周期决定查询多少条数据
        Integer cycle = bookingRule.getCycle();
        //获取当天的放号时间
        DateTime stopTime = getDateTime(new Date(), bookingRule.getStopTime());
        //如果当前时间已经超过结束时间时，周期延后一天
        if (stopTime.isBeforeNow()) {
            cycle++;
        }
        //将可预约挂号的日期存入集合中
        List<Date> dates = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime dateTime = new DateTime();
            dates.add(new DateTime(dateTime.plusDays(i).toString("yyyy-MM-dd")).toDate());
        }

        //设定分页数据
        int start = (page - 1) * limit;
        int end = limit * (page - 1) + limit;
        List<Date> pageDateList = new ArrayList<>();
        if (end > dates.size()) {
            pageDateList.addAll(dates);
            end = dates.size();
        }
        //否则要进行分页显示
        //将数据分页==> 也就是将数据分成小于等于7为一份放入到pageDateList中
        for (int i = start; i < end; i++) {
            pageDateList.add(dates.get(i));
        }
        //创建分页对象,将数据封装到分页对象中
        IPage<Date> datePage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(start, limit, dates.size());
        datePage.setRecords(pageDateList);
        datePage.setTotal(dates.size());
        return datePage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
    }

    private Schedule packageSchedule(Schedule schedule) {
        Map<String, Object> param = schedule.getParam();
        param.put("hosname", hospService.getHospitalByHoscode(schedule.getHoscode()).getHosname());
        param.put("depname", departmentService.getByDepcode(schedule.getDepcode()).getDepname());
        param.put("dayOfWeek", DateUtils.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }
}
